package com.kws.merchant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.common.config.constant.MinioCommonBucket;
import com.kws.common.core.domain.R;
import com.kws.common.core.exception.ServiceException;
import com.kws.common.security.auth.AuthUtil;
import com.kws.common.security.utils.SecurityUtils;
import com.kws.merchant.config.MinioAPI;
import com.kws.merchant.domain.UserAuthEntity;
import com.kws.merchant.domain.po.UserAuthPo;
import com.kws.merchant.domain.vo.AccountManagementVo;
import com.kws.merchant.mapper.UserAuthMapper;
import com.kws.merchant.service.UserAuthService;
import com.kws.merchant.util.FileUtil;
import com.kws.system.api.RemoteToolService;
import com.kws.system.api.domain.ResultDto;
import com.kws.system.api.domain.Rq.UserDto;
import com.kws.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : zhangbenting
 * @date : 2024/11/20 16:57
 * @Version: 1.0
 */
@Service
public class UserAuthServiceImpl extends ServiceImpl<UserAuthMapper, UserAuthEntity> implements UserAuthService {

    @Autowired
    private FileUtil fileUtil;

    @Autowired
    private RemoteToolService remoteToolService;

    @Autowired
    private MinioAPI minioAPI;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean identityAuth(UserAuthPo userAuthPo) {
        // 校验认证类型
        final int REAL_NAME_AUTH = 0;
        final int OTHER_AUTH = 1;

        Integer authType = userAuthPo.getAuthType();
        if (authType == null || (authType != REAL_NAME_AUTH && authType != OTHER_AUTH)) {
            throw new ServiceException("认证类型错误");
        }
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        LambdaQueryWrapper<UserAuthEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserAuthEntity::getUserId, userId);
        UserAuthEntity authEntity = this.getOne(wrapper);
        if (ObjectUtils.isNotNull(authEntity)) throw new RuntimeException("该用户，已存在实名认证信息");
        // 实名认证逻辑
        if (authType == REAL_NAME_AUTH) {
            UserDto userDto = new UserDto();
            userDto.setUserName(userAuthPo.getSubjectPerson());
            userDto.setIdCard(userAuthPo.getCertificateNumber());

            R<ResultDto> response = remoteToolService.eVerify(userDto);

            if (response == null || 0 != (response.getData().getCode())) {
                throw new RuntimeException("实名认证失败" + response.getMsg());
            }

            //修改sys_user
            baseMapper.updateUserInfo(userAuthPo.getSubjectPerson(), userId);
        }

        // 创建认证实体
        UserAuthEntity userAuthEntity = new UserAuthEntity();
        userAuthEntity.setUserId(userId);
        userAuthEntity.setAuthType(userAuthPo.getAuthType());
        userAuthEntity.setSubjectPerson(userAuthPo.getSubjectPerson());
        userAuthEntity.setCertificateNumber(userAuthPo.getCertificateNumber());
        userAuthEntity.setCertificateFront(userAuthPo.getCertificateFront());
        userAuthEntity.setCertificateBack(userAuthPo.getCertificateBack());

        // 拼接其他照片
        List<String> otherPhoto = userAuthPo.getOtherPhoto();
        if (otherPhoto != null && !otherPhoto.isEmpty()) {
            String otherPhotoStr = String.join("kws:", otherPhoto) + "kws:";
            userAuthEntity.setOtherPhoto(otherPhotoStr);
        } else {
            userAuthEntity.setOtherPhoto("");
        }
        return save(userAuthEntity);
    }


    @Override
    public AccountManagementVo accountManagement() {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        AccountManagementVo accountManagementVo = baseMapper.accountManagement(userId);
        if (StringUtils.isNotEmpty(accountManagementVo.getHeadImg())) {
            accountManagementVo.setHeadImg(fileUtil.fixFileName() + accountManagementVo.getHeadImg());
        }
        return accountManagementVo;
    }

    @Override
    public UserAuthPo getUserIdentityAuthInfo(Long userId) {
        LambdaQueryWrapper<UserAuthEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserAuthEntity::getUserId, userId);
        UserAuthEntity userAuthEntity = this.getOne(wrapper);
        if (ObjectUtils.isNotNull(userAuthEntity)) {
            UserAuthPo userAuthPo = new UserAuthPo();
            userAuthPo.setAuthType(userAuthEntity.getAuthType());
            userAuthPo.setCertificateBack(userAuthEntity.getCertificateBack());
            userAuthPo.setCertificateFront(userAuthEntity.getCertificateFront());
            userAuthPo.setCertificateNumber(userAuthEntity.getCertificateNumber());
            userAuthPo.setSubjectPerson(userAuthEntity.getSubjectPerson());
            String otherPhoto = userAuthEntity.getOtherPhoto();
            if (StringUtils.isNotEmpty(otherPhoto)) {
                String[] split = otherPhoto.split("kws:");
                List<String> imgList = new ArrayList<>();
                for (String s : split) {
                    String img = fileUtil.fixFileName() + s;
                    imgList.add(img);
                }
                userAuthPo.setOtherPhoto(imgList);
            }
            return userAuthPo;
        }
        return null;
    }

    @Override
    public boolean updateAccount(AccountManagementVo accountManagementVo) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        SysUser userById = baseMapper.getUserById(userId);
        if (ObjectUtils.isNull(userById)) throw new ServiceException("用户不存在");
        String img = "";
        if (StringUtils.isNotEmpty(accountManagementVo.getHeadImg())) {
            String headImg = accountManagementVo.getHeadImg();
            img = fileUtil.subFileName(headImg);
            if (!img.equals(userById.getAvatar())) {
                removeFile(userById.getAvatar());
            }
        }
        return baseMapper.updateUser(accountManagementVo.getPhone(), accountManagementVo.getSex(), img, userId);
    }

    public boolean removeFile(String url) {
        try {
            minioAPI.deleteFile(MinioCommonBucket.HUATAI_PUB_BUCKET, url);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
